package com.xsy.glsurfaceview

import android.content.Context
import android.opengl.GLES30
import android.opengl.GLSurfaceView
import android.util.AttributeSet
import android.util.Log
import com.xsy.glsurfaceview.utils.ShaderUtils
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class MyGLSurfaceView(context: Context, attributeSet: AttributeSet) :
    GLSurfaceView(context, attributeSet) {
        private var render: MyGLRender
    init {
        setEGLContextClientVersion(3)
        val fragmentShaderCode = ShaderUtils.readFileFromAssets(context, Triangle3.fragment_file_path)
        val vertexShaderCode = ShaderUtils.readFileFromAssets(context, Triangle3.vertex_file_path)
        Log.d("MyGLSurfaceView", "fragment shader code: $fragmentShaderCode")
        Log.d("MyGLSurfaceView", "vertex shader code: $vertexShaderCode")
        render = MyGLRender(vertexShaderCode, fragmentShaderCode)
        setRenderer(render)
        render
    }
    fun onDestroy() {
        render.onDestroy()
    }
}

class MyGLRender(private val vertexShaderCode: String, private val fragmentShaderCode: String) :
    GLSurfaceView.Renderer {
    private lateinit var triangle: Triangle3
    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        GLES30.glClearColor(1.0f, 0.0f, 0.0f, 1.0f)

        triangle = Triangle3(vertexShaderCode, fragmentShaderCode)
    }

    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        GLES30.glViewport(0, 0, width, height)
        Log.d("MyGLSurfaceView", "width: $width")
        Log.d("MyGLSurfaceView", "height: $height")
    }

    override fun onDrawFrame(gl: GL10?) {
        GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
        triangle.draw()
    }

    fun onDestroy(){
        triangle.onDestroy()
    }

}